//
//  catreader.cpp
//  graph-tool
//
//  Created by Armin Lunkeit on 17.02.14.
//  Copyright (c) 2014 Armin Lunkeit. All rights reserved.
//

#include "catreader.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <memory>
#include <string>

std::vector<std::string> split(const std::string& s, char seperator);

PMultiGraph initFromCAT( const std::string& file )
{
    PMultiGraph graph = std::make_shared<MultiGraph>();
    
    std::ifstream f;
    std::string line;
    
    f.open(file);
    
    uint32_t vertices;
    uint32_t edges;
    
    std::string tvertices = "vertices:";
    std::string tedges = "edges:";
    
    while( std::getline( f, line ))
    {
        //std::cout << "line: " << line << std::endl;
        
        if( 0 == memcmp( tvertices.c_str(), line.c_str(), tvertices.size() ))
        {
            std::vector<std::string> tokens = split( line, ':' );
            
            tokens = split( tokens[1], ';' );
            
            std::cout << "Count of vertices: " << tokens[ 0 ] << std::endl;
            
            vertices = (uint32_t)stoll( tokens[ 0 ]);
        }
        
        if( 0 == memcmp( tedges.c_str(), line.c_str(), tedges.size() ))
        {
            std::vector<std::string> tokens = split( line, ':' );
            
            tokens = split( tokens[1], ';' );
            
            std::cout << "Count of vertices: " << tokens[ 0 ] << std::endl;
            
            edges = (uint32_t)stoll( tokens[ 0 ]);
        }
    }
    
    f.close();
    
    return graph;
}

std::vector<std::string> split(const std::string& s, char seperator)
{
    std::vector<std::string> output;
    
    std::string::size_type prev_pos = 0, pos = 0;
    
    while((pos = s.find(seperator, pos)) != std::string::npos)
    {
        std::string substring( s.substr(prev_pos, pos-prev_pos) );
        
        output.push_back(substring);
        
        prev_pos = ++pos;
    }
    
    output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word
    
    return output;
}